package cn.huobi.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
@Component
public class LoginFilter extends ZuulFilter {

    /**
     *  过滤器执行时机
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 过滤器执行顺序
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否执行run方法
     * @return
     */
    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        String requestURI = currentContext.getRequest().getRequestURI();
        if(requestURI.endsWith("login") || requestURI.endsWith("register")){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletResponse response = currentContext.getResponse();
        response.setContentType("application/json;charset=utf-8");
        String token = currentContext.getRequest().getHeader("token");
        if(StringUtils.isEmpty(token)){
            try {
                PrintWriter writer = response.getWriter();
                Map<String, Object> map = new HashMap<>();
                map.put("success", false);
                map.put("message", "未登录！");
                map.put("requestObj", "noLogin");
                String jsonString = JSON.toJSONString(map);
                writer.write(jsonString);
                writer.close();
                currentContext.setSendZuulResponse(false);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }
}
